﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Web.Caching;
using Aandelendelen.Caching;

namespace Aandelendelen.Obs
{
	public class TopBanner : ICacheable
	{
		public static string CacheName = "data_topbanner"; 

		string href = "";
		string url = "";
		string alt = "";
		DateTime startDate;
		DateTime endDate;

		public TopBanner()
		{
			InitCacheKey();

			this.Read();
		}

		private void Read()
		{
			DateTime now = DateTime.Today;

			string path = HttpContext.Current.Server.MapPath("/App_Data/TopBanner.xml");

			XmlDocument doc = new XmlDocument();

			doc.Load(path);

			XmlNodeList nodes = doc.SelectNodes("/aandelendelen/topbanner");

			string lhref = "";
			string lurl = "";
			string lalt = "";
			DateTime lstart = new DateTime();
			DateTime lend = new DateTime();

			if (nodes != null)
			{
				foreach (XmlNode node in nodes)
				{
					foreach (XmlAttribute attr in node.Attributes)
					{
						switch (attr.LocalName)
						{
							case "href": lhref = attr.Value; break;
							case "url": lurl = attr.Value; break;
							case "alt": lalt = attr.Value; break;
							case "start": lstart = DateTime.Parse(attr.Value); break;
							case "end": lend = DateTime.Parse(attr.Value); break;
						}
					}

					if (lstart <= now && lend > now)
					{
						this.href = lhref;
						this.url = lurl;
						this.alt = lalt;
						this.startDate = lstart;
						this.endDate = lend;

						break;
					}
				}
			}

			if (string.IsNullOrEmpty(this.href))
			{
				XmlNode defaultNode = doc.SelectSingleNode("/aandelendelen/defaultbanner");

				if (defaultNode != null)
				{
					this.href = defaultNode.Attributes["href"].Value;
					this.url = defaultNode.Attributes["url"].Value;
					this.alt = defaultNode.Attributes["alt"].Value;
				}
			}
		}

		public string Href
		{
			get { return this.href; }
		}

		public string Url
		{
			get { return this.url; }
		}

		public string Alt
		{
			get { return this.alt; }
		}

		public static TopBanner GetInstance()
		{
			return DataCache.GetCacheableObject<TopBanner>(CacheName);
		}

		public static TopBanner GetInstance(string cacheKey)
		{
			return DataCache.GetCacheableObject<TopBanner>(cacheKey);
		}

		#region ICacheable
		public CacheKey CacheKey { get; set; }

		public void CacheThis(string cacheKey)
		{
			this.CacheKey.CacheThis(cacheKey);
		}

		public void InitCacheKey()
		{
			CacheKey = new CacheKey()
			{
				CacheDependency = new CacheDependency(HttpContext.Current.Server.MapPath("/App_Data/TopBanner.xml")),
				SecondsBeforeInvalidate = 86400,
				ObjectToCache = this
			};
		}
		#endregion

	}
}